/*  J
**  Date 2007-06-25 21:38:49 
**  File call.c  v 1.0
**  Author Mucker
**  See Copyright Notice in J.h
**  
*/

#include "J.h"

#include "call.h"
#include "chuck.h"
#include "mem.h"
#include "table.h"

Jcall * call_newJcall(chuck *ck)
{
	Jcall *call = Mnewvector(Jcall);

	call->ck = ck;
	call->type = J_CALL;
	call->isC = 0;
	call->env = tab_new(0);
	
	return call;
}




void  reallocCI(call_state *cs, int nsize)
{
    call_info *ostart =cs->ci_start ;

	Mrnvector(cs->ci_start, cs->sCi, nsize, call_info);

	cs->sCi = nsize;

	cs->ci = cs->ci + (cs->ci_start-ostart);

	cs->ci_end = cs->ci_start+cs->sCi -1;
}
static call_info *growCI(call_state *cs)
{
	reallocCI(cs, 2*cs->sCi);
    return ++cs->ci;
}
#define Mcall_increase(cs) ((cs->ci == cs->ci_end)?growCI(cs):++cs->ci)


#define Msavestack(cs, tag) cast(int, ( (char *) (tag)- (char *) cs->stack ))
#define Mgetcall(cs, n) ((Jtag *)((char *)cs->stack + (n)))


void call_precall(call_state *cs, JPtag call)
{
	Jcall *Jc = cast(Jcall*, call->value.obj);

	int index_call = Msavestack(cs, call);

	if(!Jc->isC){
		call_info *ci;
		JPtag base;
		chuck *ck = Jc->ck;
		
		call = Mgetcall(cs, index_call);
		base = call+1;

		ci = Mcall_increase(cs);

		ci->call = call;
		ci->base = cs->base = base;

		ci->I = cs->I = Jc->ck->I;
	
	}
}
void call_return(call_state *cs)
{
	cs--;
}